package org.example.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.mapper.*;
import org.example.pojo.*;
import org.example.service.InventoryService;
import org.example.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

@Service
public class InventoryServiceImpl implements InventoryService {
    @Autowired
    private InventoryMapper inventoryMapper;
    @Autowired
    private OrderMapper orderMapper;


    /**
     * 库存列表
     */
    @Override
    public PageBean<Inventory> list(Integer pageNum, Integer pageSize, String goodsName, Integer category) {
        PageHelper.startPage(pageNum, pageSize);
        Page<Inventory> page = inventoryMapper.list(goodsName, category);
        return new PageBean<>(page.getTotal(), page.getResult());
    }

    /**
     * 查询待库存列表
     */
    @Override
    public PageBean<StockInVo> stockInList(Integer pageNum, Integer pageSize, String orderNo, String startTime, String endTime) {
        PageHelper.startPage(pageNum, pageSize);
        // 帮我把String类型的startTime，endTime转换成LocalDateTime类型
        LocalDateTime startTime1 = null;
        LocalDateTime endTime1 = null;
        if (startTime != null || endTime != null) {
            startTime1 = LocalDateTime.parse(startTime);
            endTime1 = LocalDateTime.parse(endTime);
        }
        Page<StockInVo> page = orderMapper.stockInList(orderNo, startTime1, endTime1);
        return new PageBean<>(page.getTotal(), page.getResult());
    }

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private StockInMapper stockInMapper;

    /**
     * 库存入库
     */
    @Override
    @Transactional
    public void stockIn(stockInDto stockInDto) {
        // 状态为已入库的订单，不允许再次入库
        Integer status = orderMapper.getOrderById(stockInDto.getOrderId());
        if (status == 3) {
            throw new RuntimeException("该订单已入库，不允许再次入库");
        }
        // 更新库存表信息
        stockInDto.getDetails().forEach(stockInDetail -> {
            // 先从商品表中查询该商品是否已注册，如果没有注册，则不允许入库
            Goods byName = goodsMapper.getByName(Goods.builder().goodsName(stockInDetail.getProductName()).build());
            if (byName == null) {
                throw new RuntimeException("该商品未注册，不允许入库");
            }
            stockInDetail.setLastUpdated(LocalDateTime.now());
            // 更新库存表信息
            inventoryMapper.update(stockInDetail);
            // 更新入库表信息
            stockInDetail.setRemark(stockInDto.getRemark());
            Map<String, Object> o = ThreadLocalUtil.get();
            stockInDetail.setOperator(o.get("username").toString());
            stockInDetail.setOrderId(stockInDto.getOrderId());
            stockInDetail.setOperatorId((Integer) o.get("id"));
            System.out.println(stockInDetail);
            stockInMapper.insert(stockInDetail);
        });
        // 更新订单表信息
        orderMapper.update(Order.builder().id(stockInDto.getOrderId()).status(3).build());
    }

//    /**
//     * 库存出库
//     */
//    @Override
//    public PageBean<StockOutVo> stockOutList(Integer pageNum, Integer pageSize, String goodsName, String startTime, String endTime) {
//        PageHelper.startPage(pageNum, pageSize);
//        Page<StockOutVo> page = inventoryMapper.stockOutList(goodsName, startTime, endTime);
//        return new PageBean<>(page.getTotal(), page.getResult());
//    }
//
//    /**
//     * 库存出库详情
//     */
//    @Override
//    public StockOutVo detail(Integer id) {
//        return inventoryMapper.getStockOutByGoodsId(id);
//    }
//
//    /**
//     * 库存出库
//     */
//    @Override
//    @Transactional
//    public void stockOut(Map<String, Object> map) {
//        Integer productId = (Integer) map.get("productId");
//        Integer quantity = (Integer) map.get("quantity");
//        String remark = (String) map.get("remark");
//        // 查询库存是否充足
//        Integer quantity1 = inventoryMapper.getByGoodsId(productId);
//        if (quantity1 < quantity) {
//            throw new RuntimeException("库存不足，请重新输入数量");
//        }
//        // 更新库存表信息
//        inventoryMapper.stockOut(productId, quantity);
//        // 更新出库表信息
//        StockOutVo sov = inventoryMapper.getStockOutByGoodsId(productId);
//        Map<String, Object> o = ThreadLocalUtil.get();
//        StockOutVo stockOutVo = StockOutVo.builder()
//                .id(sov.getId())
//                .goodsName(sov.getGoodsName())
//                .stockQuantity(quantity1 - quantity)
//                .location(sov.getLocation())
//                .operator((String) o.get("username"))
//                .operatorId((Integer) o.get("id"))
//                .remark(remark)
//                .build();
//        inventoryMapper.addStockOut(stockOutVo);
//    }

    @Autowired
    private OutboundOrderMapper outboundOrderMapper;
    @Autowired
    private OutboundDetailMapper outboundDetailMapper;

    /**
     * 新增出库单
     *
     * @param dto
     */
    @Override
    @Transactional
    public String outboundAdd(OutboundDto dto) {
        // 新增出库表信息
        // 生成出库单
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String orderId = "OB" + now.format(formatter);
        // 计算出库总数
        int count = 0;
        for (outBoundItem detail : dto.getDetails()) {
            count += detail.getQuantity();
        }
        // 获取当前用户id
        Map<String, Object> o = ThreadLocalUtil.get();
        Integer id = (Integer) o.get("id");
        OutboundOrder outBoundOrder = OutboundOrder.builder()
                .orderId(orderId)
                .orderType(dto.getOrderType())
                .customerId(dto.getCustomerId())
                .toWarehouseId(dto.getToWarehouseId())
                .totalQuantity(count)
                .operatorId(id)
                .build();
        // 出库单保存到出库表中
        outboundOrderMapper.insert(outBoundOrder);
        // 详情保存到出库详情表中
        for (outBoundItem detail : dto.getDetails()) {
            outBoundItem item = outBoundItem.builder()
                    .orderId(orderId)
                    .productId(detail.getProductId())
                    .productName(detail.getProductName())
                    .quantity(detail.getQuantity())
                    .build();
            outboundDetailMapper.insert(item);
//            // 修改库存表库存信息,先查询库存是否充足
            Integer quantity = inventoryMapper.getByGoodsId(detail.getProductId());
            if (quantity < detail.getQuantity()) {
                throw new RuntimeException(detail.getProductName() + "库存不足，请重新输入数量");
            }
//            inventoryMapper.stockOut(detail.getProductId(), detail.getQuantity());
        }

        return orderId;
    }


    /**
     * 出库单列表
     */
    @Override
    public PageBean<OutboundOrderVo> outboundList(int pageNum, int pageSize, String orderId, Integer orderType, String startTime, String endTime) {
        PageHelper.startPage(pageNum, pageSize);
        Page<OutboundOrderVo> page = outboundOrderMapper.list(orderId, orderType, startTime, endTime);
        return new PageBean<>(page.getTotal(), page.getResult());
    }

    /**
     * 出库单详情
     */
    @Override
    public OutboundOrderVo outboundDetail(String orderId) {
        return outboundOrderMapper.getById(orderId);
    }

    /**
     * 审批出库单
     */
    @Override
    public void approve(String orderId) {
        OutboundOrderVo outboundOrderVo = outboundOrderMapper.getById(orderId);
        // 如果出库单状态为已出库，则不允许审批
        if (outboundOrderVo.getStatus() == 1) {
            throw new RuntimeException("该出库单已出库，不允许审批");
        }
        // 修改状态，并且修改库存表库存
        outboundOrderMapper.update(OutboundOrder.builder()
                .orderId(orderId)
                .status(1)
                .build());
        outboundOrderVo.getDetails().forEach(detail -> {
            inventoryMapper.stockOut(detail.getProductId(), detail.getQuantity());
        });
    }

    /**
     * 删除出库单
     */
    @Override
    public void delete(String orderId) {
        // 删除出库单和出库详情
        // 先删除出库详情
        outboundDetailMapper.delete(orderId);
        // 再删除出库单
        outboundOrderMapper.delete(orderId);
    }
}
